//1.引入router
var express = require('express');
var router = express.Router();

//2.引入mongoose的数据模块
var mongoose = require('mongoose');
var Goods = require('../models/goods');
var Users = require('../models/user');

//3.连接数据库
// mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/dumall', {server: {auto_reconnect: true,poolSize: 10}});

mongoose.connection.on('connected', () => {
    console.log('数据库连接成功！');
});

mongoose.connection.on('error', () => {
    console.log('数据库连接失败！');
});

mongoose.connection.on('disconnected', () => {
    console.log('数据库连接断开！');
});


/* GET goods listing. */
router.get('/list', function (req, res, next) {
    let priceOrder = req.param("priceOrder");
    let priceMin = parseInt(req.param("priceMin"));
    let priceMax = parseInt(req.param("priceMax"));
    let pageSize = parseInt(req.param("pageSize"));
    let pageNo = parseInt(req.param("pageNo"));
    let findParam = {};
    if (!isNaN(priceMin) && !isNaN(priceMax)){
        findParam = {
            salePrice: {
                $gte: priceMin,
                $lte: priceMax,
            }
        }
    }
   
    let goodsModel = Goods.find(findParam).skip((pageNo-1) * pageSize).limit(pageSize);
    let order = priceOrder == "ascend" ? 1 : -1;
    goodsModel.sort({ "salePrice": order})
    goodsModel.exec(function (err, doc) {
        if (err) {
            res.json({
                status: '1',
                msg: err.message
            });
        } else {
            res.json({
                status: '0',
                msg: '',
                result: {
                    count: doc.length,
                    list: doc
                }
            });
        }
    })
});

router.post("/addCart", function (req, res, next) {
    var userId = req.cookies.userId, productId = req.body.productId;

    Users.findOne({ userId: userId }, function (err, userDoc) {
        if (err) {
            res.json({
                status: "1",
                msg: err.message
            })
        } else {
            console.log("userDoc:" + userDoc);
            if (userDoc) {
                var goodsItem = '';
                userDoc.cartList.forEach(function (item) {
                    if (item.productid == productId) {
                        goodsItem = item;
                        item.productNum++;
                    }
                });
                if (goodsItem) {
                    userDoc.save(function (err2, doc2) {
                        if (err2) {
                            res.json({
                                status: "1",
                                msg: err2.message
                            })
                        } else {
                            res.json({
                                status: '0',
                                msg: '',
                                result: 'suc'
                            })
                        }
                    })
                } else {
                    Goods.findOne({ productid: productId }, function (err1, doc) {
                        if (err1) {
                            res.json({
                                status: "1",
                                msg: err1.message
                            })
                        } else {
                            if (doc) {
                                doc.productNum = 1;
                                doc.checked = 1;
                                userDoc.cartList.push(doc);
                                userDoc.save(function (err2, doc2) {
                                    if (err2) {
                                        res.json({
                                            status: "1",
                                            msg: err2.message
                                        })
                                    } else {
                                        res.json({
                                            status: '0',
                                            msg: '',
                                            result: 'suc'
                                        })
                                    }
                                })
                                // userDoc.update({})
                            }
                        }
                    });
                }
            }
        }
    })
})

module.exports = router;

//6.暴露路由
